import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MyBatisUtil {
	private static SqlSessionFactory sqlSessionFactory = null;//全局共享
	private static ThreadLocal<SqlSession> th=new ThreadLocal<SqlSession>();//定义一个线程变量(供一个线程共享的变量)
	static {
		try {
			String resource = "mybatis-config.xml";
			InputStream inputStream = Resources.getResourceAsStream(resource);
			sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		} catch (Exception ex) {
			ex.printStackTrace();
			throw new RuntimeException(ex);
		}
	}

	public static SqlSession openSession() {
		//如果线程变量里已经有一个属于自己的SqlSession，就用回它
		if(th.get()!=null)
			return th.get();
		//如果线程变量没有值，就创建一个新的SqlSession放入线程变量，供后续使用
		SqlSession session= sqlSessionFactory.openSession();
		th.set(session);
		return session;
	}
	
	public static void closeSession(){
		SqlSession session=th.get();
		if(session!=null){
			session.close();
			th.remove();//删掉关闭了session的残留
		}
		
			
	}
	
}







